package Stack_Queue.stack;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

//基于数组的顺序栈实现
public class MyStack<E> {
    //当前栈数据个数
    private int size;
    //实际存储数据的数组，用动态数组 - ArrayList
    private List<E> data = new ArrayList<>();

    //入栈操作
    public void push(E val) {
        //默认尾插
        data.add(val);
        size++;
    }

    //出栈操作
    public E pop() {
        if (isEmpty()) {
            //栈为空
            throw new NoSuchElementException("stack is empty!");
        }
        //删除栈顶元素
        E val = data.remove(size - 1);
        size--;
        return val;
        //上边三句等同于 return data.remove(--size);
    }

    //返回栈顶元素
    public E peek() {
        if (isEmpty()) {
            //栈为空
            throw new NoSuchElementException("stack is empty!");
        }
        return data.get(size - 1);
    }

    //判断栈空
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < size; i++) {
            sb.append(data.get(i));
            if (i != size - 1) {
                //没有到达栈底
                sb.append(",");
            }
        }
        sb.append("]-top");
        return sb.toString();
    }
}
